﻿''' <summary>
''' 车载历史数据查询
''' 何湘红 20091111 修改
''' </summary>
''' <remarks></remarks>
Public Class HDTimeCarForm
    Private projectId As String
    Private id As String
    Private projectName As String
    Private startTime As String
    Private endTime As String
    Private BeginAddress As String
    Private EndAddress As String
    Private Carrier As String
    Private carHDList As IList(Of ProjectInfo.CarHDItem) = Nothing
    Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Sub New(ByVal projectId As String, ByVal id As String, ByVal projectName As String, ByVal startTime As String, ByVal endTime As String, ByVal BenginAddress As String, ByVal EndAddress As String, ByVal Carrier As String)
        MyClass.New()
        Me.projectId = projectId
        Me.id = id
        Me.projectName = projectName
        Me.startTime = startTime
        Me.endTime = endTime
        Me.BeginAddress = BenginAddress
        Me.EndAddress = EndAddress
        Me.Carrier = Carrier
    End Sub
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()

    End Sub

    Private Sub HDTimeCarForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToParent()
        Me.Text = Me.projectName + " >>> 车载数据查询"
        Init()
    End Sub


    Private Sub InitDGVDetails()
        Me.dgvDetails.Columns.Clear() '先复位
        Me.dgvDetails.Rows.Clear()

        Me.dgvDetails.Columns.Add("details", "")
        Me.dgvDetails.Columns.Add("AI1", "AI1")
        Me.dgvDetails.Columns.Add("AI2", "AI2")
        Me.dgvDetails.Columns.Add("AI3", "AI3")
        Me.dgvDetails.Columns.Add("AI4", "RH1")
        Me.dgvDetails.Rows.Add(2)
        Me.dgvDetails.Columns("AI1").HeaderText = "AI1"
        Me.dgvDetails.Columns("AI2").HeaderText = "AI2"
        Me.dgvDetails.Columns("AI3").HeaderText = "AI3"
        Me.dgvDetails.Columns("AI4").HeaderText = "RH1"

        Me.dgvDetails.Rows(0).Cells("details").Value = "最大值"
        Me.dgvDetails.Rows(1).Cells("details").Value = "最小值"
        Me.dgvDetails.Rows(2).Cells("details").Value = "平均值"
        Me.dgvDetails.Columns("details").DefaultCellStyle.BackColor = System.Drawing.SystemColors.Control

        Me.dgvDetails.Rows(0).Cells("AI1").Value = GetMaxValue("AI1")
        Me.dgvDetails.Rows(0).Cells("AI2").Value = GetMaxValue("AI2")
        Me.dgvDetails.Rows(0).Cells("AI3").Value = GetMaxValue("AI3")
        Me.dgvDetails.Rows(0).Cells("AI4").Value = GetMaxValue("AI4")

        Me.dgvDetails.Rows(1).Cells("AI1").Value = GetMinValue("AI1")
        Me.dgvDetails.Rows(1).Cells("AI2").Value = GetMinValue("AI2")
        Me.dgvDetails.Rows(1).Cells("AI3").Value = GetMinValue("AI3")
        Me.dgvDetails.Rows(1).Cells("AI4").Value = GetMinValue("AI4")

        Me.dgvDetails.Rows(2).Cells("AI1").Value = GetAvgValue("AI1")
        Me.dgvDetails.Rows(2).Cells("AI2").Value = GetAvgValue("AI2")
        Me.dgvDetails.Rows(2).Cells("AI3").Value = GetAvgValue("AI3")
        Me.dgvDetails.Rows(2).Cells("AI4").Value = GetAvgValue("AI4")

        dgvDetails.Refresh()
    End Sub

    ''' <summary>
    ''' 获取端口最小值
    ''' </summary>
    ''' <param name="AI"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetMinValue(ByVal AI As String) As String
        Dim count As Integer = carHDList.Count
        If count > 0 Then


            Dim minValue As Decimal = 0.0
            If AI.Equals("AI1") Then
                Dim min As Decimal

                If carHDList(0).AI1.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI1
                End If

                For Each car As ProjectInfo.CarHDItem In carHDList


                    If car.AI1.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min > car.AI1 Then
                            min = car.AI1
                        End If
                    End If



                Next
                minValue = min

            ElseIf AI.Equals("AI2") Then
                Dim min As Decimal

                If carHDList(0).AI2.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI2
                End If

                For Each car As ProjectInfo.CarHDItem In carHDList


                    If car.AI2.Equals("---") Then
                        'min = -300
                        Continue For
                    Else
                        If min > car.AI2 Then
                            min = car.AI2
                        End If
                    End If



                Next
                minValue = min

            ElseIf AI.Equals("AI3") Then
                Dim min As Decimal

                If carHDList(0).AI3.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI3
                End If

                For Each car As ProjectInfo.CarHDItem In carHDList


                    If car.AI3.Equals("---") Then
                        'min = -300
                        Continue For
                    Else
                        If min > car.AI3 Then
                            min = car.AI3
                        End If
                    End If



                Next
                minValue = min

            ElseIf AI.Equals("AI4") Then
                Dim min As Decimal

                If carHDList(0).AI4.Equals("---") Then
                    min = -300

                Else
                    min = carHDList(0).AI4
                End If

                For Each car As ProjectInfo.CarHDItem In carHDList


                    If car.AI4.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min > car.AI4 Then
                            min = car.AI4
                        End If
                    End If

                   

                Next
                minValue = min

            End If

            If minValue = -300 Then
                Return "---"
            Else
                Return minValue.ToString
            End If


        Else
            Return "---"
        End If



    End Function

    ''' <summary>
    ''' 获取端口最大值
    ''' </summary>
    ''' <param name="AI">要获取的端口</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetMaxValue(ByVal AI As String) As String
        Dim maxValue As Decimal = 0.0
        Dim count As Integer = carHDList.Count
        If count > 0 Then



            If AI.Equals("AI1") Then
                Dim min As Decimal
                If carHDList(0).AI1.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI1
                End If


                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI1.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min < car.AI1 Then
                            min = car.AI1
                        End If
                    End If
                Next
                maxValue = min

            ElseIf AI.Equals("AI2") Then
                Dim min As Decimal
                If carHDList(0).AI2.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI2
                End If


                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI2.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min < car.AI2 Then
                            min = car.AI2
                        End If
                    End If
                Next
                maxValue = min

            ElseIf AI.Equals("AI3") Then
                Dim min As Decimal
                If carHDList(0).AI3.Equals("---") Then
                    min = -300
                Else
                    min = carHDList(0).AI3
                End If


                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI3.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min < car.AI3 Then
                            min = car.AI3
                        End If
                    End If
                Next
                maxValue = min

            ElseIf AI.Equals("AI4") Then

                Dim min As Decimal
                If carHDList(0).AI4.Equals("---") Then
                    min = -300

                Else
                    min = carHDList(0).AI4
                End If


                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI4.Equals("---") Then
                        ' min = -300
                        Continue For
                    Else
                        If min < car.AI4 Then
                            min = car.AI4
                        End If
                    End If
                Next
                maxValue = min

            End If

            If maxValue = -300 Then
                Return "---"
            Else
                Return maxValue.ToString

            End If



        Else
            Return "---"
        End If

    End Function

    ''' <summary>
    ''' 获取端口平均值
    ''' </summary>
    ''' <param name="AI">要获取的端口</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetAvgValue(ByVal AI As String) As String
        Dim agvValue As Decimal = 0
        Dim count As Integer = carHDList.Count

        If count > 0 Then

            If AI.Equals("AI1") Then
                Dim avg As Decimal = 0
                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI1.Equals("---") Then
                        'avg += -300
                        Continue For
                    Else
                        avg += car.AI1
                    End If


                Next
                agvValue = (avg / count).ToString
            ElseIf AI.Equals("AI2") Then
                Dim avg As Decimal = 0
                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI2.Equals("---") Then
                        'avg += -300
                        Continue For
                    Else
                        avg += car.AI2
                    End If


                Next
                agvValue = (avg / count).ToString
            ElseIf AI.Equals("AI3") Then
                Dim avg As Decimal = 0
                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI3.Equals("---") Then
                        'avg += -300
                        Continue For
                    Else
                        avg += car.AI3
                    End If


                Next
                agvValue = (avg / count).ToString
            ElseIf AI.Equals("AI4") Then
                Dim avg As Decimal = 0
                For Each car As ProjectInfo.CarHDItem In carHDList

                    If car.AI4.Equals("---") Then
                        'avg += -300
                        Continue For
                    Else
                        avg += car.AI4
                    End If


                Next
                agvValue = (avg / count).ToString
            End If
            Dim temp As Double = System.Math.Round(agvValue, 2, MidpointRounding.AwayFromZero)

            If temp = -300 Then
                Return "---"
            Else
                Return temp.ToString
            End If


        Else
            Return "---"
        End If

    End Function


    '格式化查询的DataGridView的数据
    Public Sub FormatDataGridView()
        For i As Integer = 0 To dgvHDTimeDataSelect.RowCount - 1
            For j As Integer = 0 To dgvHDTimeDataSelect.ColumnCount - 1
                Dim AlarmStatus As String = dgvHDTimeDataSelect.Rows(i).Cells("AlarmStatus").Value

                If AlarmStatus.Equals("2") Or AlarmStatus.Equals("正常") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AlarmStatus").Value = "正常"
                ElseIf AlarmStatus.Equals("1") Or AlarmStatus.Equals("报警") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AlarmStatus").Value = "报警"
                    Dim cell As DataGridViewCell = Me.dgvHDTimeDataSelect.Rows(i).Cells("AlarmStatus") '获取这列
                    cell.Style.ForeColor = Color.Red '设置红色
              
                End If

                Dim a1 As String = dgvHDTimeDataSelect.Rows(i).Cells("AI1").Value
                If a1.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AI1").Value = "---"

                End If
                Dim a2 As String = dgvHDTimeDataSelect.Rows(i).Cells("AI2").Value
                If a2.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AI2").Value = "---"

                End If
                Dim a3 As String = dgvHDTimeDataSelect.Rows(i).Cells("AI3").Value
                If a3.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AI3").Value = "---"

                End If
                Dim a4 As String = dgvHDTimeDataSelect.Rows(i).Cells("AI4").Value
                If a4.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AI4").Value = "---"

                End If

                Dim amax As String = dgvHDTimeDataSelect.Rows(i).Cells("Mintemper").Value
                If amax.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("Mintemper").Value = "---"

                End If
                Dim amin As String = dgvHDTimeDataSelect.Rows(i).Cells("MaxTemper").Value
                If amin.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("MaxTemper").Value = "---"

                End If
                Dim aavg As String = dgvHDTimeDataSelect.Rows(i).Cells("AvgTemper").Value
                If aavg.Equals("-300.00") Then
                    dgvHDTimeDataSelect.Rows(i).Cells("AvgTemper").Value = "---"

                End If
            Next
        Next
    End Sub


    Public Sub GetCarHDList()
        Me.dgvHDTimeDataSelect.AutoGenerateColumns = False
        Dim timeValue As String = (CInt(Me.txtStartStopTime.Text) * CInt(Me.txtNumber.Text)).ToString

        carHDList = CarHDService.GetHDCarList(Me.id, Me.projectId, Me.startTime, Me.endTime, timeValue)

        dgvHDTimeDataSelect.DataSource = carHDList
        FormatDataGridView() '格式化DataGridView数据，也就是格式化历史数据显示的样式

        InitDGVDetails() '最大值，最小值，平均值
    End Sub

    Public Sub Init()
        Me.txtProjectName.Text = projectName
        Me.dtpFrom.Text = startTime
        Me.dtpTo.Text = endTime
        Me.txtBeginAddress.Text = BeginAddress
        Me.txtEndAddress.Text = EndAddress
        Me.txtCarrier.Text = Carrier
        Me.txtStartStopTime.Text = CarHDStartUpService.GetStartStopSpace(projectId, id)
    End Sub

    '点击查询按钮的时候
    Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        GetCarHDList()
    End Sub
    Dim cols(100) As String
    Dim headers(100) As String
    Dim tArray As New ArrayList()
    Dim hArray As New ArrayList()
    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        Print()
        'ExportDataGridView(Me.dgvHDTimeDataSelect)
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub Print()
        Dim dt As IList(Of ProjectInfo.CarHDItem)
        dt = CType(Me.dgvHDTimeDataSelect.DataSource, IList(Of ProjectInfo.CarHDItem))
        If dt Is Nothing OrElse dt.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim objExcel As New Excel.Application

        Dim wb As Excel.Workbook = objExcel.Workbooks.Add(True)

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.dgvHDTimeDataSelect.Columns.Count - 1
            If Me.dgvHDTimeDataSelect.Columns(i).Visible Then
                index += 1
                cols(index) = Me.dgvHDTimeDataSelect.Columns(i).DataPropertyName
                headers(index) = Me.dgvHDTimeDataSelect.Columns(i).HeaderText
            End If
        Next

        ReDim Preserve cols(index)

        'Dim bRow As Integer = dt.Rows.Count
        ''Dim values(,) As Object
        Dim values(dt.Count, cols.Length + 1) As Object 'cols.Length + 1:时间为2列


        For j As Integer = 0 To cols.Length
            If j > 1 Then
                values(0, j + 1) = headers(j) 'j+1:跳过时间2列(共2列)
            Else
                values(0, j) = headers(j)
            End If
        Next

        '
        For i As Integer = 0 To dt.Count - 1
            Dim r As ProjectInfo.CarHDItem = dt.Item(i)
            values(i + 1, 0) = i + 1
            For j As Integer = 1 To cols.Length - 1 '跳过GridView第一列
                If j > 1 Then
                    values(i + 1, j + 1) = dgvHDTimeDataSelect.Rows(i).Cells(cols(j).ToString).Value ' r(cols(j)) 'j+1:跳过时间2列(共2列)
                Else
                    values(i + 1, j) = dgvHDTimeDataSelect.Rows(i).Cells(cols(j).ToString).Value 'r(cols(j))
                End If
            Next
        Next

        'Get stat values
        Dim statValues(3, Me.dgvHDTimeDataSelect.Columns.Count) As Object
        For i As Integer = 0 To statValues.GetLength(0) - 1 'init values
            For j As Integer = 0 To statValues.GetLength(1) - 1
                statValues(i, j) = String.Empty
            Next
        Next
        For i As Integer = 0 To Me.dgvDetails.Rows.Count - 1 '3
            Dim r As DataGridViewRow = Me.dgvDetails.Rows(i)
            For j As Integer = 0 To Me.dgvDetails.Columns.Count - 1
                statValues(i, j) = r.Cells(j).Value
            Next j
        Next i

        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            'objExcel.Visible = True
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Value = values
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(bRow, cols.Length)).Value = values

            '设置格式
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10

            '序号
            objExcel.Range("A1", "A" & (dt.Count + 1)).ColumnWidth = 5
            'objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).RowHeight = 20

            '监控时间
            'objExcel.Range("B1", objExcel.Cells(dt.Count + 1, 2)).Insert(Excel.XlInsertShiftDirection.xlShiftToRight) '插入合并列
            objExcel.Range("B1", objExcel.Cells(dt.Count + 1, 3)).ColumnWidth = 12
            objExcel.Range("B1", objExcel.Cells(dt.Count + 1, 3)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            Dim totalIndex As Integer = 4 + tArray.Count + hArray.Count
            '设置温湿度列宽; 2008.10.31
            'objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Count + 1, totalIndex)).ColumnWidth = 6
            'objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Count + 1, totalIndex)).NumberFormatLocal = "0.00"

            '设置温湿度统计列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, 26)).ColumnWidth = 8
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, 26)).NumberFormatLocal = "0.00"
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Count + 1, totalIndex - 1 + IIf(tArray.Count > 0, 3, 0) + IIf(hArray.Count > 0, 3, 0))).Interior.Color = RGB(255, 221, 221) 'array.count > 0

            'Dim pageRow As Integer = 27 '不包括统计的3行; 2008.10.31
            Dim statRow As Integer = 3
            Dim totalCount As Integer = Math.Ceiling(dt.Count / 30) * 30 - statRow
            If totalCount < dt.Count Then
                totalCount += statRow
            End If
            '合并单元格
            Dim range As Excel.Range
            range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3)) '合并日期单元格(dt.Rows.Count); 2008.10.31
            range.Merge(True)
            'For i As Integer = 1 To totalCount + 1
            '    range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3))
            '    range.Merge(True)
            'Next
            '合并统计单元格
            range = objExcel.Range(objExcel.Cells(totalCount + 2, 1), objExcel.Cells(totalCount + 4, 2)) '2008.10.31
            'range = objExcel.Range(objExcel.Cells(bRow - 2, 1), objExcel.Cells(bRow, 2))
            range.Merge()
            range.Value2 = "统计"
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            range.Font.Size = 20

            'cols.Length + 1:时间为2列
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Count + 1, cols.Length + 1)).Value2 = values

            '添加统计信息
            Dim statRange As Excel.Range
            statRange = objExcel.Range(objExcel.Cells(totalCount + 2, 3), objExcel.Cells(totalCount + 4, cols.Length + 1)) '2008.10.31
            'statRange = objExcel.Range(objExcel.Cells(bRow - 2, 3), objExcel.Cells(bRow, cols.Length + 1))
            statRange.Value2 = statValues
            'statRange.Interior.Color = RGB(221, 221, 221)
            'statRange.Interior.Pattern = 4
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Color = RGB(221, 221, 221)
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Pattern = 4

            '设置边框
            range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(totalCount + 4, cols.Length + 1))
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            objExcel.Columns.AutoFit() '列宽自动
            '设置保护
            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            '温湿度值
            Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            With ws.PageSetup
                .LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .CenterHeader = String.Format("&""宋体,加粗""&28 {0}温/湿度历史数据查询 ", Me.txtProjectName.Text)
                .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.6)
                .RightMargin = objExcel.Application.InchesToPoints(0.4)
                .TopMargin = objExcel.Application.InchesToPoints(1.08)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                '.PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                .Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                '.PrintArea = "A1:U" & bRow
                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"

                Try

                    With .LeftHeaderPicture
                        .Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\ClientLogo.jpg"
                        .Height = 68
                        .Width = 68
                        '.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoFalse
                        .LockAspectRatio = 0
                    End With

                Catch ex As Exception
                    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                    Debug.WriteLine("页眉图片" & ex.ToString())
                End Try

            End With
            'excel.printpreview()
            'excel.PrintPreview()

            objExcel.Visible = True
            'objExcel.ActiveWindow.View = Excel.XlWindowView.xlPageBreakPreview
            objExcel.ActiveWindow.SelectedSheets.PrintPreview()
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                If objExcel.ActiveWindow.View = Excel.XlWindowView.xlNormalView Then '分页预览
                    'objExcel.ActiveSheet.Unprotect(pwd)
                    wb.Close(False, False)
                    objExcel.Workbooks.Close()
                    objExcel.DisplayAlerts = False
                    objExcel.Quit()
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                    wb = Nothing
                    objExcel = Nothing
                    GC.Collect()
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        End Try
    End Sub

    Private Sub ExportDataGridView(ByVal dgv As DataGridView)

        If dgv.Rows.Count = 0 Then
            msg.Show("没有数据！")
            Exit Sub
        Else
            ' Excel.Application(Excel = New Excel.Application())
            Dim excel As Excel.Application = New Excel.Application
            excel.Application.Workbooks.Add(True)
            excel.Visible = True
            '生产字段名
            For i As Integer = 0 To dgv.ColumnCount - 1

                If dgv.Columns(i).Visible Then
                    excel.Cells(1, i + 1) = dgv.Columns(i).HeaderText
                End If


            Next

            For i As Integer = 0 To dgv.RowCount - 1
                For j As Integer = 0 To dgv.ColumnCount - 1

                    If dgv(j, i).ValueType.Name.Equals("String") Then
                        excel.Cells(i + 2, j + 1) = "" + dgv(j, i).Value.ToString


                    Else
                        excel.Cells(i + 2, j + 1) = dgv(j, i).Value

                    End If
                Next
            Next
        End If

    End Sub

    Private Sub dgvHDTimeDataSelect_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles dgvHDTimeDataSelect.DataBindingComplete
        '从新排序一下列
        Me.dgvHDTimeDataSelect.Columns("UpdateTime").DisplayIndex = 0
        Me.dgvHDTimeDataSelect.Columns("UpdateTime").Width = 150
        Me.dgvHDTimeDataSelect.Columns("AI1").DisplayIndex = 1
        Me.dgvHDTimeDataSelect.Columns("AI2").DisplayIndex = 2
        Me.dgvHDTimeDataSelect.Columns("AI3").DisplayIndex = 3
        Me.dgvHDTimeDataSelect.Columns("AI4").DisplayIndex = 4
        Me.dgvHDTimeDataSelect.Columns("Latitude").DisplayIndex = 5
        Me.dgvHDTimeDataSelect.Columns("Longitude").DisplayIndex = 6
        Me.dgvHDTimeDataSelect.Columns("MinTemper").DisplayIndex = 7
        Me.dgvHDTimeDataSelect.Columns("MaxTemper").DisplayIndex = 8
        Me.dgvHDTimeDataSelect.Columns("AvgTemper").DisplayIndex = 9
        Me.dgvHDTimeDataSelect.Columns("AlarmStatus").DisplayIndex = 10

    End Sub


End Class